import { fetch } from 'whatwg-fetch';
import { parseParam } from '@/utils/urlUtil';
import ep from '@/utils/eventproxy';
import storejs from 'storejs';
import { requestAfter } from '@/events/rxEvent';
import { notification } from 'antd';

// token错误code
var toeknErrorCode = ['101001', '101002', '101003', '101004'];

export default function request(url, options, host) {
  //默认设置
  let defaultOptions = {
    method: 'GET',
    mode: 'cors',
    credentials: 'omit',
    params: {},
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      Accept: 'application/json',
      Authorization: storejs.get('token') || '',
    },
  };

  let newOptions = { ...defaultOptions, ...options };
  newOptions.headers = { ...defaultOptions.headers, ...options.headers };

  // 设置url
  url = parseParam(url, options.params);
  // 删除body
  if (newOptions.method == 'GET') delete newOptions.body;

  return fetch(host + url, newOptions)
    .then(async response => {
      var status = response.status;
      var data = await response.json();

      // rx事件
      requestAfter.next({ url, newOptions, host, status, data });

      //正常情况 200-300
      if (response.status >= 200 && response.status < 300) {
        if (toeknErrorCode.indexOf(data.subCode) != -1)
          ep.emit('tokenError', data);
        return data;
      }

      // 报错抛出错误 400-500
      if (status >= 400 || status >= 500) {
        const error = new Error();
        error.response = response;
        error.data = data;
        throw error;
      }
    })
    .catch(async e => {
      if (e.data) {
        var data = e.data;
        if (toeknErrorCode.indexOf(data.subCode) != -1) ep.emit('tokenError', data);
        if (toeknErrorCode.indexOf(data.subCode) == -1) {
          var env = process.env.environment;
          if (env == 'dev' || env == 'localhost') {
            // notification.open({
            //   message: '发生异常',
            //   description: data.subMsg,
            //   duration: 0,
            // });
          }
        }
        return e.data;
      }
      return {
        code: 503,
        msg: 'Link server timeout',
        subCode: '',
        subMsg: '503',
        timestamp: '',
        data: {},
        verificationFailedMsgList: [],
        success: false,
        fail: true,
      };
    });
}
